import React, { Component } from 'react'
import { NavBar, Icon, Flex, Toast } from 'antd-mobile'
import './WorthBuy.scss'
import axios from '../../utils/myaxios'
import { Carousel } from 'antd-mobile';
import guanggao from '../../assets/images/guanggao.png'
import miaosha from '../../assets/images/miaoshaImg.png'
import baoyou from '../../assets/images/9.9baoyou.png'
import pintuan from '../../assets/images/pintuan.png'
import cuxiao from '../../assets/images/cuxiao.png'

export default class WorthBuy extends Component {
  constructor(props) {
    super(props);
    this.box = React.createRef();
    this.contentRef = React.createRef();
  }
  state = {
    guanData: [], /* 分页导航数据 */
    iconData: [],
    Data: [], /* 促销数据 */
    Columns: [], /* 秒杀 */
    msList: [],
    msList2: [],
    msList3: [],
    msList4: [],
    msList5: [],
    rename2: [],
    rename3: [],
    rename4: [],
    // bangdan: [],
    // jiagou: [],
    baoyou: [],
    pintuan: [],
    guanzhu: [],
    cuxiao: [],
    remai: [],
    tuijian: [],
    page: ['1', '2'],
    backTop: true,
  }

  componentDidMount() {
    // 导航分页数据
    axios
      .get("/api/touch/optimization/info?udid=6965ca3f8d167912ffd85cc527e45d41&permanent_id=20200921085728177632016758503555234&client_version=1.0&app_id=touch&h5_server=1&user_client=touch&ct=touch&cv=1.0&ts=1600673492702&tc=1c8c950379da66b5130ed5ef6ceced34")
      .then((res) => {
        // console.log(res);
        this.setState({
          guanData: res.result.guanData,
          iconData: res.result.iconData,
        })
      })
      .catch((err) => console.log(err));
    // 促销数据
    axios.get("/mapi7/index.php?c=promotion&a=hot-promotion&imageSize=b&udid=52707142f04ca2bb9a7251cd17ae30b9&permanent_id=20200921085552454446427990770715880&client_version=1.0&app_id=touch&h5_server=1&user_client=touch&timestamp=1600739629668&time_code=372899bb53a28358efc642babed0eaea")
      .then((res) => {
        // console.log(res);
        // let arr = res.data.length
        this.setState({
          Data: res.data.slice(0, 6),
        })
      })
    // 即刻秒杀
    axios.get("/api/touch/optimization/feed?page=0&udid=6965ca3f8d167912ffd85cc527e45d41&permanent_id=20200921085728177632016758503555234&client_version=1.0&app_id=touch&h5_server=1&user_client=touch&ct=touch&cv=1.0&ts=1600752088350&tc=352920bc24913e8c553acda857ccbc2b")
      .then((res) => {
        // console.log(res.result.columns[0].infos);
        let ms_data = res.result.columns[0];
        let ms_data3 = res.result.columns[5];
        let ms_data4 = res.result.columns[10];
        let ms_data5 = res.result.columns[15];

        let newMs_arr = ms_data.infos.map(v => ({
          product_id: v.productId,
          couponModel: v.couponModel,
          price: v.originPrice,
          image_url: v.productImageUrl,
          dd_sale_price: v.salePrice,
          name: v.productName,
          promotionName: v.promotionName,
          promotionTag: v.promotionTag,
        }))
        let newMs_arr3 = ms_data3.infos.map(v => ({
          product_id: v.productId,
          couponModel: v.couponModel,
          price: v.originPrice,
          image_url: v.productImageUrl,
          dd_sale_price: v.salePrice,
          name: v.productName,
          promotionName: v.promotionName,
          promotionTag: v.promotionTag,
        }))
        let newMs_arr4 = ms_data4.infos.map(v => ({
          product_id: v.productId,
          couponModel: v.couponModel,
          price: v.originPrice,
          image_url: v.productImageUrl,
          dd_sale_price: v.salePrice,
          name: v.productName,
          promotionName: v.promotionName,
          promotionTag: v.promotionTag,
        }))
        let newMs_arr5 = ms_data5.infos.map(v => ({
          product_id: v.productId,
          couponModel: v.couponModel,
          price: v.originPrice,
          image_url: v.productImageUrl,
          dd_sale_price: v.salePrice,
          name: v.productName,
          promotionName: v.promotionName,
          promotionTag: v.promotionTag,
        }))
        this.setState({
          Columns: res.result.columns[0].infos.slice(0, 10),
          baoyou: res.result.columns[5].infos.slice(0, 6),
          pintuan: res.result.columns[10].infos.slice(0, 6),
          cuxiao: res.result.columns[15].infos.slice(0, 6),
          // tuijian: res.result.columns[20].infos.slice(0, 6),
          msList: newMs_arr,
          msList3: newMs_arr3,
          msList4: newMs_arr4,
          msList5: newMs_arr5,

        })
      })
    // 畅销榜
    axios.get("/api/touch/optimization/feed?page=0&udid=6965ca3f8d167912ffd85cc527e45d41&permanent_id=20200921085728177632016758503555234&client_version=1.0&app_id=touch&h5_server=1&user_client=touch&ct=touch&cv=1.0&ts=1600761291545&tc=4d1384da13bbbd80844f4e18016a15d8")
      .then((res) => {
        let newarr = []
        res.result.columns.slice(1, 5).forEach(element => {
          newarr.push(element.infos)
        });
        let newMs_arr2 = newarr.map(v => {
          return {
            averageScore: v[0].averageScore,
            commentCount: v[0].commentCount,
            num: v[0].num,
            product_id: v[0].productId,
            couponModel: v[0].couponModel,
            price: v[0].originPrice,
            image_url: v[0].productImageUrl,
            dd_sale_price: v[0].salePrice,
            name: v[0].productName,
            promotionName: v[0].promotionName,
            promotionTag: v[0].promotionTag,
          }
        })
        this.setState({
          bangdan: newarr,
          msList2: newMs_arr2
        })
      })

    // 加购榜
    axios.get("/api/touch/optimization/feed?page=0&udid=6965ca3f8d167912ffd85cc527e45d41&permanent_id=20200921085728177632016758503555234&client_version=1.0&app_id=touch&h5_server=1&user_client=touch&ct=touch&cv=1.0&ts=1600761291545&tc=4d1384da13bbbd80844f4e18016a15d8")
      .then((res) => {
        let newarr2 = []
        res.result.columns.slice(6, 10).forEach(element => {
          newarr2.push(element.infos)
        });
        let newMs_arr6 = newarr2.map(v => {
          return {
            averageScore: v[0].averageScore,
            commentCount: v[0].commentCount,
            num: v[0].num,
            product_id: v[0].productId,
            couponModel: v[0].couponModel,
            price: v[0].originPrice,
            image_url: v[0].productImageUrl,
            dd_sale_price: v[0].salePrice,
            name: v[0].productName,
            promotionName: v[0].promotionName,
            promotionTag: v[0].promotionTag,
          }
        })
        this.setState({
          jiagou: newarr2,
          rename2: newMs_arr6

        })
      })

    // 关注
    axios.get("/api/touch/optimization/feed?page=0&udid=6965ca3f8d167912ffd85cc527e45d41&permanent_id=20200921085728177632016758503555234&client_version=1.0&app_id=touch&h5_server=1&user_client=touch&ct=touch&cv=1.0&ts=1600761291545&tc=4d1384da13bbbd80844f4e18016a15d8")
      .then((res) => {
        let newarr3 = []
        res.result.columns.slice(11, 15).forEach(element => {
          newarr3.push(element.infos)
        });
        let newMs_arr7 = newarr3.map(v => {
          return {
            averageScore: v[0].averageScore,
            commentCount: v[0].commentCount,
            num: v[0].num,
            product_id: v[0].productId,
            couponModel: v[0].couponModel,
            price: v[0].originPrice,
            image_url: v[0].productImageUrl,
            dd_sale_price: v[0].salePrice,
            name: v[0].productName,
            promotionName: v[0].promotionName,
            promotionTag: v[0].promotionTag,
          }
        })
        this.setState({
          guanzhu: newarr3,
          rename3: newMs_arr7

        })
      })

    // 热卖榜
    axios.get("/api/touch/optimization/feed?page=0&udid=6965ca3f8d167912ffd85cc527e45d41&permanent_id=20200921085728177632016758503555234&client_version=1.0&app_id=touch&h5_server=1&user_client=touch&ct=touch&cv=1.0&ts=1600761291545&tc=4d1384da13bbbd80844f4e18016a15d8")
      .then((res) => {
        let newarr2 = []
        res.result.columns.slice(16, 20).forEach(element => {
          newarr2.push(element.infos)
        });
        this.setState({
          remai: newarr2
        })
      })
  }

  // 点击进入分类
  handleFenyeItemClick = (params) => {
    this.props.history.push('/category');
  }
  handleListItemClick = (title) => {
    this.props.history.push('/goodList' + title);
  }
  handlegoodDetailClick = (goods_info) => {
    this.props.history.push({
      pathname: "/goodDetail",
      state: { goods_info: goods_info }
    })
  }
  toLogin = () => {
    this.props.history.push('/login');
  }
  toRegister = () => {
    this.props.history.push('/register');
  }



  // 滚动事件
  handleScroll = () => {
    console.log(111);
    let parentElement = this.contentRef.current.parentElement;
    let scrollTop = parentElement.scrollTop; // 列表已经滚动的高度
    if (scrollTop > 1200) {
      this.setState({
        backTop: true,
      });
    } else {
      this.setState({
        backTop: false,
      });
    }
  };
  // 回到顶部
  // backToTop = () => {
  //   let scrollTop = this.contentRef.current.parentElement.scrollTop;
  //   let myTimer = setInterval(() => {
  //     scrollTop -= 50;
  //     if (scrollTop <= 0) {
  //       scrollTop = 0;
  //       window.clearInterval(myTimer);
  //     }
  //     this.contentRef.current.parentElement.scrollTo(0,scrollTop);
  //   },10);
  // }
  ToTop = (params) => {
    if (this.ListView) this.ListView.scrollTop = 0;
  }



  // 从榜单添加到购物车
  handleIntocart = (params) => {
    // e.stopPropagation();
    // 先从本地缓存中获取购物车数据
    let carts = JSON.parse(localStorage.getItem('carts') || '[]');
    // 获取productId
    let { productId } = this.props.match.params;
    let index = carts.findIndex((v) => {
      return v.productId === productId ? true : false
    }
    )
    // index === -1
    if (index === -1) {
      let bang_info = this.state.bangdan[0];
      // 第一次添加数量是1
      bang_info.memberNum = 1;
      // 在购物车中默认被选中
      bang_info.checked = true;
      carts.push(bang_info);
    } else {
      // 第n次添加
      carts[index].memberNum++;
    }
    Toast.success('加入购物车成功', 1);
    localStorage.setItem('carts', JSON.stringify(carts[0][0]));
  }




  render() {
    return (
      <div ref={(el) => (this.ListView = el)}>
        <img src={guanggao} alt="" className="advertise" />
        {/* 顶栏 */}
        <div className="dang-nav">
          <NavBar
            className="nav-bar"
            mode="light"
            icon={<Icon type="left" />}
            onLeftClick={() => window.history.go(-1)}
            rightContent={[<Icon key="1" type="ellipsis" />]}
          >
            值得买
          </NavBar>
        </div>
        {/* 顶栏 */}
        {/* 分页导航 */}
        <div className="dang-fenye">
          <div className="fenye-items">
            <Flex>
              {this.state.guanData &&
                this.state.guanData.map((v) => {
                  // console.log(v);
                  return (
                    <Flex.Item
                      key={v.iconImageUrl}
                      onClick={this.handleFenyeItemClick}
                    >
                      <img src={v.iconImageUrl} alt="" />
                    </Flex.Item>
                  );
                })}
            </Flex>
            <Flex>
              {this.state.iconData.map((v) => {
                return (
                  <Flex.Item
                    key={v.iconImageUrl}
                    onClick={this.handleFenyeItemClick}
                  >
                    <img src={v.iconImageUrl} alt="" />
                  </Flex.Item>
                );
              })}
            </Flex>
          </div>
        </div>
        {/* 分页导航 */}
        {/* 促销专场 */}
        <div className="cuxiao-items">
          <div className="cuxiao-title">
            <span className="cuxiao-title-mid">促销专场</span>
            <span className="cuxiao-title-right">更多&gt;</span>
          </div>
          <div className="cuxiao-list">
            {this.state.Data.map((v) => {
              return (
                <div
                  key={v.promotion_id}
                  className="list-items"
                  onClick={this.handleListItemClick.bind(this, v.promotion_id)}
                >
                  <div className="cuxiao-list-title">{v.title}</div>
                  <img src={v.img_url[0]} alt="" />
                </div>
              );
            })}
          </div>
        </div>
        {/* 促销专场 */}
        {/* 即刻秒杀 */}
        <div className="miaosha-items">
          <div className="miaosha-title">
            <img src={miaosha} alt="" className="miaosha-title-mid" />
            <span className="miaosha-title-right">更多&gt;</span>
          </div>
          <Carousel dots={false}>
            {this.state.page.map((val) => (
              <div
                key={val}
                ref={this.box}
                className="miaosha-list"
                style={{ width: "100%" }}
              >
                {this.state.msList.map((v) => {
                  return (
                    <div
                      key={v.product_id}
                      className="list-items"
                      onClick={this.handlegoodDetailClick.bind(this, v)}
                    >
                      <img src={v.image_url} alt="" />
                      <div className="miaosha-list-title">{v.name}</div>
                      <p className="price-sale">￥{v.dd_sale_price}</p>
                      <p className="price-origin">￥{v.price}</p>
                    </div>
                  );
                })}
              </div>
            ))}
          </Carousel>
        </div>
        {/* 即刻秒杀 */}
        {/* 畅销榜 */}
        <div className="slaehot">
          {this.state.msList2 && this.state.msList2.map((v) => {
            return (
              <div
                key={v.product_id}
                className="salehot-list"
                onClick={this.handlegoodDetailClick.bind(this, v)}
              >
                <div className="paiming">
                  <div className="bangnum">畅销榜第{v.num}名</div>
                  <span>更多&gt;</span>
                </div>
                <div className="list-bigbox">
                  <img src={v.image_url} alt="" />
                  <div className="list-bigbox-right">
                    <h4>{v.name}</h4>
                    <div className="bigbox-right-middle">
                      <div className="product-price">
                        <span className="slae-price">
                          ￥{v.dd_sale_price}
                        </span>
                        <span className="origin-price">￥{v.price}</span>
                      </div>
                    </div>
                    <div className="bigbox-right-bottom">
                      <em className="iconfont icon-pinglun1">
                        {v.commentCount}
                      </em>
                      <em className="iconfont icon-wuxing">
                        {v.averageScore}
                      </em>
                      <i
                        className="iconfont icon-gouwuche3"
                        onClick={this.handleIntocart.bind(
                          this,
                          v.product_id
                        )}
                      ></i>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        {/* 畅销榜 */}
        {/* 9.9包邮 */}
        <div className="miaosha-items baoyou-items">
          <div className="miaosha-title">
            <img src={baoyou} alt="" className="miaosha-title-mid" />
            <span className="miaosha-title-right">更多&gt;</span>
          </div>
          <Carousel dots={false}>
            {this.state.page.map((val) => (
              <div key={val} className="miaosha-list" style={{ width: "100%" }}>
                {this.state.msList3.map((v) => {
                  return (
                    <div
                      key={v.product_id}
                      className="list-items"
                      onClick={this.handlegoodDetailClick.bind(
                        this,
                        v
                      )}
                    >
                      <img src={v.image_url} alt="" />
                      <div className="miaosha-list-title">{v.name}</div>
                      <p className="price-sale">￥{v.dd_sale_price}</p>
                      <p className="price-origin">￥{v.price}</p>
                    </div>
                  );
                })}
              </div>
            ))}
          </Carousel>
        </div>
        {/* 9.9包邮 */}
        {/* 加购 */}
        <div className="slaehot">
          {this.state.rename2 && this.state.rename2.map((v) => {
            return (
              <div
                className="salehot-list"
                key={v.product_id}
                onClick={this.handlegoodDetailClick.bind(this, v)}
              >
                <div className="paiming">
                  <div className="bangnum jiagounum">已被{v.num}人加购</div>
                  <span>更多&gt;</span>
                </div>
                <div className="list-bigbox">
                  <img src={v.image_url} alt="" />
                  <div className="list-bigbox-right">
                    <h4>{v.name}</h4>
                    <div className="bigbox-right-middle">
                      <div className="product-price">
                        <span className="slae-price">￥{v.dd_sale_price}</span>
                        <span className="origin-price">
                          ￥{v.price}
                        </span>
                      </div>
                    </div>
                    <div className="bigbox-right-bottom">
                      <em className="iconfont icon-pinglun1">
                        {v.commentCount}
                      </em>
                      <em className="iconfont icon-wuxing">
                        {v.averageScore}
                      </em>
                      <i className="iconfont icon-gouwuche3"></i>
                    </div>
                  </div>
                </div>
              </div> 
            )
          }
          )}
          
        </div>
        {/* 加购 */}
        {/* 拼团 */}
        <div className="miaosha-items pintuan-items">
          <div className="miaosha-title">
            <img src={pintuan} alt="" className="miaosha-title-mid" />
            <span className="miaosha-title-right">更多&gt;</span>
          </div>
          <Carousel dots={false}>
            {this.state.page.map((val) => (
              <div key={val} className="miaosha-list" style={{ width: "33%" }}>
                {this.state.msList4.map((v) => {
                  return (
                    <div
                      key={v.product_id}
                      className="list-items"
                      onClick={this.handlegoodDetailClick.bind(
                        this,
                        v
                      )}
                    >
                      <img src={v.image_url} alt="" />
                      <div className="miaosha-list-title">{v.name}</div>
                      <p className="price-sale">￥{v.dd_sale_price}</p>
                      <p className="price-origin">￥{v.price}</p>
                    </div>
                  );
                })}
              </div>
            ))}
          </Carousel>
        </div>
        {/* 拼团 */}
        {/* 关注 */}
        <div className="slaehot">
          {this.state.rename3.map((v) => {
            // console.log(v[0]);
            return (
              <div
                className="salehot-list"
                key={v.product_id}
                onClick={this.handlegoodDetailClick.bind(this, v)}
              >
                <div className="paiming">
                  <div className="bangnum guanzhunum ">
                    已被{v.num}人关注
                  </div>
                  <span>更多&gt;</span>
                </div>
                <div className="list-bigbox">
                  <img src={v.image_url} alt="" />
                  <div className="list-bigbox-right">
                    <h4>{v.name}</h4>
                    <div className="bigbox-right-middle">
                      <div className="product-price">
                        <span className="slae-price">￥{v.dd_sale_price}</span>
                        <span className="origin-price">
                          ￥{v.price}
                        </span>
                      </div>
                    </div>
                    <div className="bigbox-right-bottom">
                      <em className="iconfont icon-pinglun1">
                        {v.commentCount}
                      </em>
                      <em className="iconfont icon-wuxing">
                        {v.averageScore}
                      </em>
                      <i className="iconfont icon-gouwuche3"></i>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        {/* 关注 */}
        {/* 促销 */}
        <div className="miaosha-items cuxuai-items">
          <div className="miaosha-title">
            <img src={cuxiao} alt="" className="miaosha-title-mid" />
            <span className="miaosha-title-right">更多&gt;</span>
          </div>
          <Carousel dots={false}>
            {this.state.page.map((val) => (
              <div key={val} className="miaosha-list" style={{ width: "33%" }}>
                {this.state.msList5.map((v) => {
                  return (
                    <div
                      key={v.product_id}
                      className="list-items"
                      onClick={this.handlegoodDetailClick.bind(
                        this,
                        v
                      )}
                    >
                      <img src={v.image_url} alt="" />
                      <div className="miaosha-list-title">{v.name}</div>
                      <p className="price-sale">￥{v.dd_sale_price}</p>
                      <p className="price-origin">￥{v.price}</p>
                    </div>
                  );
                })}
              </div>
            ))}
          </Carousel>
        </div>
        {/* 促销 */}
        {/* 热卖榜 */}
        <div className="slaehot">
          {this.state.remai.map((v) => {
            // console.log(v[0]);
            return (
              <div
                className="salehot-list"
                key={v[0].productId}
                onClick={this.handlegoodDetailClick.bind(this, v[0].productId)}
              >
                <div className="paiming">
                  <div className="bangnum remainum ">热卖榜第{v[0].num}名</div>
                  <span>更多&gt;</span>
                </div>
                <div className="list-bigbox">
                  <img src={v[0].productImageUrl} alt="" />
                  <div className="list-bigbox-right">
                    <h4>{v[0].productName}</h4>
                    <div className="bigbox-right-middle">
                      <div className="product-price">
                        <span className="slae-price">￥{v[0].salePrice}</span>
                        <span className="origin-price">
                          ￥{v[0].originPrice}
                        </span>
                      </div>
                    </div>
                    <div className="bigbox-right-bottom">
                      <em className="iconfont icon-pinglun1">
                        {v[0].commentCount}
                      </em>
                      <em className="iconfont icon-wuxing">
                        {v[0].averageScore}
                      </em>
                      <i className="iconfont icon-gouwuche3"></i>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        {/* 热卖榜 */}
        {/* 推荐 */}
        <div className="miaosha-items tuijian-items">
          <div className="miaosha-title">
            <span className="tuijian-title">为你推荐</span>
            <span className="miaosha-title-right">更多&gt;</span>
          </div>
          <Carousel dots={false}>
            {this.state.page.map((val) => (
              <div key={val} className="miaosha-list" style={{ width: "33%" }}>
                {this.state.tuijian.map((v) => {
                  return (
                    <div
                      key={v.productId}
                      className="list-items"
                      onClick={this.handlegoodDetailClick.bind(
                        this,
                        v.productId
                      )}
                    >
                      <img src={v.productImageUrl} alt="" />
                      <div className="miaosha-list-title">{v.productName}</div>
                      <p className="price-sale">￥{v.salePrice}</p>
                      <p className="price-origin">￥{v.originPrice}</p>
                    </div>
                  );
                })}
              </div>
            ))}
          </Carousel>
        </div>
        {/* 推荐 */}
        {/* 底部 */}
        <div className="footer-item">
          <div className="lgt">
            <span className="lg">
              <em onClick={this.toLogin}>登录</em>
              <em onClick={this.toRegister}>注册</em>
            </span>
            <span className="top" onClick={this.ToTop} ref={this.contentRef}>
              <i className="iconfont icon-shangjiantou"></i>TOP
            </span>
          </div>
          <p className="computer-edition">
            <a href="http://book.dangdang.com/?_utm_brand_id=11106&_ddclickunion=460-5-biaoti|ad_type=0|sys_id=1">
              提建议
            </a>
            <a href="http://book.dangdang.com/?_utm_brand_id=11106&_ddclickunion=460-5-biaoti|ad_type=0|sys_id=1">
              电脑版
            </a>
            <a href="http://book.dangdang.com/?_utm_brand_id=11106&_ddclickunion=460-5-biaoti|ad_type=0|sys_id=1">
              帮助
            </a>
          </p>
          <p className="footer-msg">
            Copyright ©2018 北京当当网信息技术有限公司
          </p>
          <p className="footer-msg">北京市朝阳区北三环东路8号，100028</p>
        </div>
        {/* 底部 */}
      </div>
    );
  }
}
